package cn.yoyo.service;

import cn.yoyo.entity.Book;
import cn.yoyo.entity.CartBook;
import cn.yoyo.entity.SysUser;
import cn.yoyo.mapper.BookMapper;
import cn.yoyo.mapper.CartMapper;
import cn.yoyo.tools.GetUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CartServiceImpl implements CartService {
    @Autowired(required = false)
    CartMapper cartMapper;
    @Autowired(required = false)
    BookMapper bookMapper;

    @Override
    public List<CartBook> findAll(Integer uid) {
        return cartMapper.findAll(uid);
    }

    @Override
    @Transactional
    public int add(Integer bookid) {
        SysUser user = GetUser.getUser();
        int x = 0;
        Map<String, Object> map1 = new HashMap<>();
        map1.put("bookid", bookid);
        map1.put("uid", user.getId());
        // 添加到购物车时,如果该本书不存在于购物车,则添加,如果存在,则num+1
        if (cartMapper.update(map1) < 1) {
            Map<String, Object> map = new HashMap<>();
            map.put("uid", user.getId());
            map.put("bookid", bookid);
            map.put("num", 1);
            map.put("tcreate", new Date());
            x = cartMapper.add(map);
            // 成功添加到购物车之后 书本的收藏数量+1
            Book book = bookMapper.findById(bookid);
            Map<String, Object> map2 = new HashMap<>();
            map2.put("favnum", book.getFavnum() + 1);
            map2.put("id", bookid);
            bookMapper.updateRFS(map2);
        }
        return x;
    }

    @Override
    public int delete(Integer id) {
        return cartMapper.delete(id);
    }
}
